<template>
  <div class="main">
    <view @click="open" class="input" v-if="props.showTime==1">
      {{format}}
    </view>
    <uv-datetime-picker ref="datetimePicker" v-model="valueDate" :mode="mode" :minDate="props.minDate" :maxDate="props.maxDate"></uv-datetime-picker>
  </div>
</template>

<script setup lang="ts">
const instance = getCurrentInstance();
const { proxy } = getCurrentInstance();
let props = defineProps([
  "mode",
  "modelValue",
  "placeholder",
  "minDate",
  "maxDate",
  "showTime",
]);
const emit = defineEmits(["update:modelValue"]);

let mode = computed(() => {
  return props.mode ? props.mode : "date";
});

const valueDate = computed({
  get() {
    return props.modelValue
      ? Number(new Date(modelValue_format(props.modelValue)))
      : Number(new Date());
  },
  set(value: string) {
    let time = time_format(value);
    emit("update:modelValue", time);
  },
});

let modelValue_format = (value) => {
  let date = new Date();
  switch (props.mode) {
    case "month":
      date.setMonth(Number(value) - 1);
    case "year":
      date.setFullYear(value);
    default:
  }
  return date;
};

let time_format = (value) => {
  let date = "";
  switch (props.mode) {
    case "datetime":
      date = proxy.$utils.dateTimeFormateFn(value, "all");
      break;
    case "year":
      date = proxy.$utils.dateTimeFormateFn(value, "year");
      break;
    default:
      date = proxy.$utils.dateTimeFormateFn(value);
      break;
  }
  return date;
};

let format = computed(() => {
  let text = props.placeholder ? props.placeholder : "请选择时间";
  return props.modelValue ? time_format(valueDate.value) : text;
});

let open = () => {
  instance.refs.datetimePicker.open();
};

defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.main {
  width: 100%;
  .input {
    color: #808080;
    // border: 1px solid #dadbde;
    display: inline-block;
    padding: 5px 10px;
    border-radius: 2px;
    width: 100%;
  }
}
</style>
